package com.longxi.tianjintianbao.ui.presenter.assetscheck;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Base64;
import android.view.View;
import android.widget.Toast;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponseWebPd;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.greedao.controller.DataInventoryController;
import com.longxi.tianjintianbao.greedao.entity.Inventory;
import com.longxi.tianjintianbao.greedao.entity.InventoryChild;
import com.longxi.tianjintianbao.ui.activity.assetscheck.TestActivity;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.assetscheck.ITest2AtView;
import com.longxi.tianjintianbao.utils.AESUtil;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class Test2Presenter extends BasePresenter<ITest2AtView> {

    private InventoryChild inventoryChild;
    private boolean isImageUpload = true;
    private List<LocalMedia> selectList = new ArrayList<>();
    Inventory inventory;

    public Test2Presenter(BaseActivity context) {
        super(context);
    }

    public void setBar() {
        mContext.setTitle("资产详情");
        mContext.setTvLeft(MyUtils.getString(R.string.back));

        inventoryChild = DataInventoryController.getInventoryChildById(mContext.getIntent().getLongExtra(AppConst.BILLID, 0));
        inventory = DataInventoryController.getPatrolByIid(inventoryChild.iid);

        setData();
    }

    /**
     * 设置数据
     */
    private void setData() {
        if(inventoryChild == null){
            getView().getNestedscrollview().setVisibility(View.GONE);
            getView().getBtnPd().setVisibility(View.GONE);
        }else{
            getView().getNestedscrollview().setVisibility(View.VISIBLE);
            String name =
                    "资产编号:" + inventoryChild.getNumber() +
                    "\n资产分类:" + inventoryChild.getCagegory() +
                    "\n资产名称:" + inventoryChild.getName() +
                    "\n使用部门:" + inventoryChild.getDepartment() +
                    "\n存放地点:" + inventoryChild.getLocation() +
                    "\nGPS信息:" + inventoryChild.getGps() +
                    "\n型号规格:" + inventoryChild.getSpecifications() +
                    "\n计量单位:" + inventoryChild.getUnit() +
                    "\n账面数量:" + inventoryChild.getBooknum();


            if(inventoryChild.getIsdraft().equals("0")){
                getView().getEtPdsl().setText(inventoryChild.getInventorynum() == 0 ? inventoryChild.getBooknum() + "" : inventoryChild.getInventorynum() + "");
                getView().getLlEdit().setVisibility(View.VISIBLE);
                getView().getBtnPd().setVisibility(View.VISIBLE);
            }else if(inventoryChild.getIsdraft().equals("1")){
                getView().getEtPdsl().setText(inventoryChild.getInventorynum() == 0 ? inventoryChild.getBooknum() + "" : inventoryChild.getInventorynum() + "");
                getView().getLlEdit().setVisibility(View.VISIBLE);
                getView().getBtnPd().setVisibility(View.VISIBLE);

                String[] imgs = inventoryChild.getImages().split(",");
                if(imgs.length != 0 && inventoryChild.getImages().length() > 10){
                    addPicUtils.selectList.clear();
                    for (int i = 0; i < imgs.length; i++){
                        LocalMedia localMedia = new LocalMedia();
                        localMedia.setCompressPath(imgs[i]);
                        localMedia.setPath(imgs[i]);
                        addPicUtils.selectList.add(localMedia);
                    }
                    gridImageAdapter.setList(addPicUtils.selectList);
                    gridImageAdapter.notifyDataSetChanged();
                }

            }else if(inventoryChild.getIsdraft().equals("2")){
                String[] imgs = inventoryChild.getImages().split(",");

                if(imgs.length != 0 && inventoryChild.getImages().length() > 10){
                    addPicUtils.selectList.clear();
                    for (int i = 0; i < imgs.length; i++){
                        LocalMedia localMedia = new LocalMedia();
                        localMedia.setCompressPath(imgs[i]);
                        localMedia.setPath(imgs[i]);
                        addPicUtils.selectList.add(localMedia);
                    }
                    gridImageAdapter.setList(addPicUtils.selectList);
                    gridImageAdapter.notifyDataSetChanged();
                }

                name += "\n盘点数量:" + inventoryChild.getInventorynum();

                getView().getBtnPd().setVisibility(View.VISIBLE);
                getView().getBtnPd().setText("重新上传");
            }else{
                String[] imgs = inventoryChild.getImages().split(",");

                if(imgs.length != 0 && inventoryChild.getImages().length() > 10){
                    addPicUtils.selectList.clear();
                    for (int i = 0; i < imgs.length; i++){
                        LocalMedia localMedia = new LocalMedia();
                        localMedia.setCompressPath(imgs[i]);
                        localMedia.setPath(imgs[i]);
                        addPicUtils.selectList.add(localMedia);
                    }
                    gridImageAdapter.setList(addPicUtils.selectList);
                    gridImageAdapter.notifyDataSetChanged();
                }

                name += "\n盘点数量:" + inventoryChild.getInventorynum();
                getView().getLlEdit().setVisibility(View.GONE);
                getView().getRecyclerView().setVisibility(View.VISIBLE);
                getView().getBtnPd().setVisibility(View.GONE);
            }
            getView().getTvName().setText(name);
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode != mContext.RESULT_OK){
            return;
        }

        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                addPicUtils.selectList = PictureSelector.obtainMultipleResult(data);
                gridImageAdapter.setList(addPicUtils.selectList);
                gridImageAdapter.notifyDataSetChanged();
                if(inventoryChild.isdraft.equals("2") || inventoryChild.isdraft.equals("3")){
//                    uploadImage(localMedia.get(0).getCompressPath());
                    updata2("3");
                }
                break;
        }
    }

    public void onClickBtn(){
        if("0".equals(inventoryChild.isdraft) || "1".equals(inventoryChild.isdraft)){
            onPd();
        }else if("2".equals(inventoryChild.isdraft)){
            onAgainPd();
        }
    }

    /**
     * 盘点
     */
    public void onPd() {
        String sss = getView().getEtPdsl().getText().toString().trim();
        try {
            inventoryChild.inventorynum = Double.parseDouble(sss);
        } catch (NumberFormatException e) {
            inventoryChild.inventorynum = 0.0;
        }
        if(inventoryChild.inventorynum == 0){
            MyUtils.showToast("盘点数量不能为0");
            return;
        }

        if(inventoryChild.state.equals("1") && inventoryChild.inventorynum != -1){
            MyUtils.showToast("盘盈时盘点数量必须为-1，否则服务端无法保存！");
            getView().getEtPdsl().setText("-1.0");
            return;
        }

        updata("1");

//        if(addPicUtils.selectList.size() == 0){
//            updata("1");
//            return;
//        }
//
//        positionImage = 1;
//        uploadImage();

    }



    /**
     * 重新上传
     */
    public void onAgainPd() {
        getUploadData();
    }

    private int positionImage = 1;

//    private void uploadImage(String imagePath){
//
//        mContext.showWaitingDialog("图片上传中");
//
//        String usernameApassword = "";
//        try {
//            usernameApassword = MyApplication.username + ",," + AESUtil.encrypt(MyApplication.password, "1234567890123456");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        String base64 = MyUtils.imageToBase64(imagePath);
//        JSONObject object = new JSONObject();
//        String[] imgpppp = imagePath.split("/");
//
//        try {
//            object.put("type", "setData");
//            object.put("validate", usernameApassword);
//            object.put("billtype", "image");
//            object.put("billcode", AppConst.PDIMAGEQZ + imgpppp[imgpppp.length - 1]);
//            object.put("billdata", base64);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//
//        ApiRetrofit.getInstance().validate(object)
//        .subscribeOn(Schedulers.io())
//        .observeOn(AndroidSchedulers.mainThread())
//        .subscribe(new MySubscriber<BaseResponseWebPd>(mContext) {
//            @Override
//            public void onError(ExceptionHandle.ResponeThrowable throwable) {
//                mContext.hideWaitingDialog();
//                updata2("2");
//                MyUtils.showToast(throwable.message);
//            }
//
//            @Override
//            public void onNext(BaseResponseWebPd result) {
//                mContext.hideWaitingDialog();
//                if(result.getCode() != 0){
//                    MyUtils.showToast(result.getMsg());
//                    updata2("2");
//                    return;
//                }
//
//                if(result.getData().contains("ERROR")){
//                    MyUtils.showToast("图片上传失败请重新试一试");
//                    updata2("2");
//                    return;
//                }
//
//                updata2("3");
//
//            }
//        });
//    }

    private void updata(String isdraft){
        String imagePath = "";

        for (LocalMedia localMedia : addPicUtils.selectList){
            imagePath += localMedia.getCompressPath() + ",";
        }
        if(addPicUtils.selectList.size() > 0){
            inventoryChild.images = imagePath.substring(0, imagePath.length() - 1);
        }
        inventoryChild.isdraft = isdraft;
        DataInventoryController.correctSportInfo(inventoryChild);
        MyUtils.showToast("盘点成功!");
        mContext.setResult(mContext.RESULT_OK);
        mContext.finish();
    }

    private void updata2(String isdraft){
        String imagePath = "";

        for (LocalMedia localMedia : addPicUtils.selectList){
            imagePath += localMedia.getCompressPath() + ",";
        }
        if(addPicUtils.selectList.size() > 0){
            inventoryChild.images = imagePath.substring(0, imagePath.length() - 1);
        }
        inventoryChild.isdraft = isdraft;
        DataInventoryController.correctSportInfo(inventoryChild);
        MyUtils.showToast("盘点成功!");
        mContext.setResult(mContext.RESULT_OK);

        getView().getBtnPd().setVisibility(View.GONE);
    }

    private int isUploadNum = 1;//当前已上传数量
    private int haveUploadNum = 1;
    /**
     * 批量上传
     */
    private void getUploadData() {

        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        RxPermissions permissions = new RxPermissions(mContext);
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    imagePathList = Arrays.asList(inventoryChild.images.split(","));//取出images数据
                    if(!"".equals(inventoryChild.images) && imagePathList.size() > 0){//如果有图片数据 就调用上传图片的方法
                        uploadImage();
                    }else{//没有图片就将这个上传
                        uploadInventory();
                    }
                } else {
                    MyUtils.showToast(mContext.getString(R.string.picture_jurisdiction));
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 上传资产盘点信息
     */
    private void uploadInventory(){
        positionImage = 1;
        mContext.showWaitingDialog2("上传第" + isUploadNum + "条单据共" + haveUploadNum + "条单据");

        String usernameApassword = "";
        try {
            usernameApassword = MyApplication.username + ",," + AESUtil.encrypt(MyApplication.password, "1234567890123456");
        } catch (Exception e) {
            e.printStackTrace();
        }

        String[] imgs = inventoryChild.getImages().split(",");
        String img1AND2 = "";
        for (String imgPath : imgs) {
            String[] imgpppp = imgPath.split("/");
            img1AND2 += "\n" + (AppConst.PDIMAGEQZ + imgpppp[imgpppp.length - 1]).replace(".JPEG", "1.JPEG");
        }
        String billdata = inventoryChild.getNumber() + "," + inventoryChild.getInventorynum() + "," + inventoryChild.getGps() +
                "\n" + inventoryChild.getNumber() + img1AND2;

        JSONObject object = new JSONObject();
        try {
            object.put("type", "setData");
            object.put("validate", usernameApassword);
            object.put("billtype", "inventory");
            object.put("billcode", inventory.getNumber());
            object.put("billdata", billdata);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().validate(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponseWebPd>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponseWebPd result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }

                if(result.getData().contains("ERROR")){
                    MyUtils.showToast(result.getData());
                    return;
                }

                isUploadNum++;
                inventoryChild.isdraft = "2";
                MyUtils.showToast("重新上传成功!");
                DataInventoryController.correctSportInfo(inventoryChild);

            }
        });
    }

    private List<String> imagePathList = new ArrayList<>();//当前需要上传的图片
    /**
     * 搞不懂怎么想的
     * 图片上传 先调用此方法把图片上传上去 然后在上传item列表的信息
     */
    private void uploadImage(){
        mContext.showWaitingDialog2("上传第" + isUploadNum + "条单据的第" + positionImage + "张图片");
        String usernameApassword = "";
        try {
            usernameApassword = MyApplication.username + ",," + AESUtil.encrypt(MyApplication.password, "1234567890123456");
        } catch (Exception e) {
            e.printStackTrace();
        }

        String imagePath = imagePathList.get(positionImage - 1);
//        String base64 = MyUtils.imageToBase64(imagePath);

        Bitmap bitmap = MyUtils.imageZoom(imagePath, 100);
        if(bitmap == null){
            uploadInventory();
            return;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] bitmapBytes = baos.toByteArray();
        String base64 = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);

        JSONObject object = new JSONObject();
        String[] imgpppp = imagePath.split("/");

        try {
            object.put("type", "setData");
            object.put("validate", usernameApassword);
            object.put("billtype", "image");
            object.put("billcode", (AppConst.PDIMAGEQZ + imgpppp[imgpppp.length - 1]).replace(".JPEG", "1.JPEG"));
            object.put("billdata", base64);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().validate(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponseWebPd>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponseWebPd result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }

                if(result.getData().contains("ERROR")){
                    MyUtils.showToast("图片上传失败请重新试一试");
                    return;
                }

                if(positionImage < imagePathList.size()){
                    positionImage++;
                    uploadImage();
                }else{
                    uploadInventory();
                }

            }
        });
    }
}
